#include "RingQueue.hpp"
#include <iostream>
#include <pthread.h>
#include <unistd.h>

struct threaddata
{
    RingQueue *rq;
    std::string name;
};
void *Pthread(void *arg)
{
    threaddata *td = (threaddata *)arg;
    int i = 0;
 while(1)
 {
       
    sleep(2);
    std::cout << "生产者" << td->name << "生产了一个数据" << i << std::endl;
    td->rq->Queue(i);
    i++;
 }
    return nullptr;
}

// void *Cthread(void *arg)
// {
//     threaddata *td = (threaddata *)arg;
//    while(1)
//   {
//      int out;
//     td->rq->Pop(&out);
//     std::cout << "消费者" << td->name << "消费了一个数据" << out << std::endl;


// sleep(3);
        // 1. 消费任务
//         int t = 0;
//         td->rq->Pop(&t);

//         // 2. 处理任务 -- 处理任务的时候，这个任务，已经被拿到线程的上下文中了,不属于队列了
//         std::cout << td->name << " 消费者拿到了一个数据:  " << t << std::endl;
//    }
//     return nullptr;
// }

void *Cthread(void *arg)
{
    threaddata *td = (threaddata *)arg;
    while(1)
    {
        int out;
        td->rq->Pop(&out);  // 传递地址
        std::cout << "消费者" << td->name << "消费了一个数据" << out << std::endl;
    }
    return nullptr;
}

int main()
{

    // 申请阻塞队列
    RingQueue *rq = new RingQueue(5);

    pthread_t p, c;
    threaddata *td1 = new threaddata();
    td1->name = "pthread-1";
    td1->rq = rq;
    threaddata *td2 = new threaddata();
    td2->name = "cthread-1";
    td2->rq = rq;
    pthread_create(&p, nullptr, Pthread, td1);
    pthread_create(&c, nullptr, Cthread, td2);
    pthread_join(p, nullptr);
    pthread_join(c, nullptr);
    return 0;
}